package com.facesteel.speech_play

import android.content.Context
import android.os.Environment
import com.facesteel.speech_play.utils.ContextHelper
import com.facesteel.speech_play.utils.SensorUtil
import com.facesteel.speech_play.utils.SpeakerUtil
import com.facesteel.speech_play.utils.SpeechPlayer
import com.facesteel.speech_play.utils.StorageUtils
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** SpeechPlayPlugin */
class SpeechPlayPlugin: FlutterPlugin, MethodCallHandler {


  private lateinit var applicationContext: Context

  private lateinit var channel : MethodChannel

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "speech_play")
    channel.setMethodCallHandler(this)

    this.applicationContext = flutterPluginBinding.applicationContext

    ContextHelper.getInstance().setContext(this.applicationContext)

    SpeechPlayHelper.getInstance().setMethodChannel(channel)
    SpeechPlayHelper.getInstance().setDartIsReady(true)
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    when(call.method){
      "getPlatformVersion" -> {
        result.success("Android ${android.os.Build.VERSION.RELEASE}")
      }
      "getExternalFilesDir" -> {
        val path = StorageUtils.getStoragePath(this.applicationContext,
          Environment.DIRECTORY_DOWNLOADS)
        result.success(path)
      }
      "speechPlay" -> {
        @Suppress("UNCHECKED_CAST") val arguments: Map<String, Any> =
          call.arguments as Map<String, Any>
        val path = arguments["path"] as String
        val startTime = arguments["startTime"] as Int
        val duration = arguments["duration"] as Int
        SpeechPlayer.startSpeech(this.applicationContext, path, startTime, duration, result)
      }
      "pausePlay" -> {
        SpeechPlayer.pauseSpeech(result)
      }
      "cancelPause" -> {
        SpeechPlayer.cancelPause()
      }
      "playSeekTo" -> {
        @Suppress("UNCHECKED_CAST") val arguments: Map<String, Any> =
          call.arguments as Map<String, Any>
        val startTime = arguments["startTime"] as Int
        SpeechPlayer.playSeekTo(startTime)
      }
      "switchSpeaker" -> {
        @Suppress("UNCHECKED_CAST") val arguments: Map<String, Any> =
          call.arguments as Map<String, Any>
        val enable = arguments["enable"] as Boolean
        SensorUtil.switchSpeaker(this.applicationContext, enable)
      }
      else ->{
        result.notImplemented()
      }
    }

  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }
}
